<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="1100px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item prop="base64Image">
            <template #label>
              <label>图片</label>
            </template>
            <UploadImage
              v-model:file-list="fileList"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleChange"
              @on-exceed="handleExceed"
              @on-remove="handleRemove"
            >
              <template #trigger>
                <el-icon><i-ep-Plus /></el-icon>
              </template>
            </UploadImage>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="食材大类" prop="name">
            <TextInput v-model="formData.name" label="食材大类" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="食材小类" prop="name">
            <TextInput v-model="formData.name" label="食材小类" />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="食材名称" prop="name">
            <TextInput v-model="formData.name" label="食材名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="食材简介" prop="introduction">
            <TextInput v-model="formData.introduction" label="食材简介" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营养成分" prop="ingredient">
            <TextInput v-model="formData.ingredient" label="营养成分" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价值功效" prop="efficacy">
            <TextInput v-model="formData.efficacy" label="价值功效" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="食用禁忌" prop="contraindication">
            <TextInput v-model="formData.contraindication" label="食用禁忌" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="认识选购" prop="purchase">
            <TextInput v-model="formData.purchase" label="认识选购" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代表菜谱" prop="typicalRecipe">
            <TextInput v-model="formData.typicalRecipe" label="代表菜谱" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() => (props.type === 'add' ? '新建食材' : '编辑食材'))

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  type: 'material',
  base64Image: '',
  name: '',
  introduction: '',
  ingredient: '',
  efficacy: '',
  contraindication: '',
  purchase: '',
  typicalRecipe: ''
})
const rules = {
  base64Image: g_rules.uploadFileRule('图片'),
  name: g_rules.commonInputText('食材名称')
  // introduction: g_rules.commonInputText('食材简介'),
  // ingredient: g_rules.commonInputText('营养成分'),
  // efficacy: g_rules.commonInputText('价值功效'),
  // contraindication: g_rules.commonInputText('食用禁忌'),
  // purchase: g_rules.commonInputText('认识选购'),
  // typicalRecipe: g_rules.commonInputText('代表菜谱')
}
const fileList = ref([])

watch(
  () => formData.value.base64Image,
  nv => {
    nextTick(() => {
      refDialogForm.value.validateField(['base64Image'])
    })
  }
)

onMounted(() => {
  props.type === 'edit' && getFormData()
})

const getFormData = _ => {
  g_api.foodstuff
    .apiMaterialQueryDetail({ id: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = {
          ...formData.value,
          id: '',
          picturePath: ''
        }
        g_utils.assignFormData(formData.value, data)
        if (data.picturePath) {
          fileList.value = [
            {
              name: data.picturePath,
              url: g_utils.showImg(data.picturePath)
            }
          ]
          formData.value.base64Image = data.picturePath
        }
        console.log('formData.value', formData.value)
      }
    })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleChange = (file, files) => {
  console.log('handleChange', file, files)
  g_utils.fileToBase64(file.raw).then(res => {
    formData.value.base64Image = res
    formData.value.picturePath = ''
  })
}

const handleExceed = (files, uploadFiles) => {
  // console.log('handleExceed', files, uploadFiles)
  g_utils.fileToBase64(files[0]).then(res => {
    formData.value.base64Image = res
    formData.value.picturePath = ''
  })
}

const handleRemove = file => {
  console.log('handleRemove', file)
  formData.value.base64Image = ''
  formData.value.picturePath = ''
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.foodstuff.apiMaterialCreate
        : g_api.foodstuff.apiMaterialUpdate
    urlMethod({
      ...formData.value,
      base64Image: g_utils.isExternal(formData.value.base64Image)
        ? ''
        : formData.value.base64Image.replace(/^data:image\/[a-z]+;base64,/, '')
    })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss">
:deep(.el-upload-list) {
  margin-top: 0;
  .el-upload-list__item {
    line-height: 24px;
    margin-bottom: 0;
    .el-icon--close-tip {
      color: var(--main-theme);
    }
  }
  .el-upload-list__item.is-success .el-upload-list__item-name:hover {
    color: var(--main-theme);
  }
}
</style>
